package cn.xyfmzmy.strategy;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 模拟根据充值金额返回相应客服
 * 使用策略模式优化if-else
 */
@RestController
public class CustomerController {

    private Map<UserType,CustomerService> customerServiceMap;

    @Autowired
    private DefaultCustomerService defaultCustomerService;

    @GetMapping("/customer/{recharge}")
    public String customer(@PathVariable("recharge") int recharge){
        UserType userType = UserType.typeOf(recharge);
        CustomerService customerService = customerServiceMap.getOrDefault(userType,defaultCustomerService);
        return customerService.findCustomer();
    }

    @Autowired
    public void setcustomerServiceMap(List<CustomerService> customerServiceList){
        this.customerServiceMap = customerServiceList.stream()
                .filter(customerService -> customerService.getClass().isAnnotationPresent(SupportType.class))
                .collect(Collectors.toMap(this::findUserTypeFromService,Function.identity()));
        if(this.customerServiceMap.size() != UserType.values().length){
            throw new IllegalArgumentException("有用户类型没有对应的策略");
        }
    }

    private UserType findUserTypeFromService(CustomerService customerService){
        return customerService.getClass().getAnnotation(SupportType.class).value();
    }

}
